package controllers

import (
	"beego45/models"
	beego "github.com/beego/beego/v2/server/web"
	"math"
)

type Bxx struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *Bxx) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	shuliang, _ := c.GetInt("shuliang")
	num, _ := c.GetInt("num")
	ShId, _ := c.GetInt("sh_id")
	be := models.Shop{
		Name:     name,
		Price:    price,
		Shuliang: shuliang,
		Num:      num,
		ShId:     ShId,
	}
	err := models.DB.Create(&be).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *Bxx) List() {
	name := c.GetString("name")
	query := models.DB.Model(&models.Shop{})
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	query.Count(&count)
	sum := int(math.Ceil(float64(count) / float64(size)))
	offset := (page - 1) * size
	up := page - 1
	if up < 1 {
		up = 1
	}
	down := page + 1
	if down > sum {
		down = sum
	}
	var svc []models.Shop
	err := query.Preload("Sh").Limit(size).Offset(offset).Find(&svc).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData := make(map[string]interface{})
		pageData["svc"] = svc
		pageData["sum"] = sum
		pageData["up"] = up
		pageData["down"] = down
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
func (c *Bxx) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Shop{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}

}
